/**
 * 
 */
package com.googlecode.xcarve.config.refer;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;

/**
 * @author xinyun.d
 * 2014年11月1日
 */
public class ServiceReferBean<T> extends AbstractRefer<T> implements InitializingBean, FactoryBean<T>{
	static final Logger logger = LoggerFactory.getLogger(ServiceReferBean.class);
	
	@Override
	public T getObject() throws Exception {
		return getRef();
	}

	@Override
	public Class<?> getObjectType() {
		if(getInterfaceClass() != null){
			return getInterfaceClass();
		}
		if( StringUtils.isNotBlank(getInterfaceName()) && StringUtils.isNotBlank(getInterfaceName())){
			try {
				setInterfaceClass(Class.forName(getInterfaceName(), true, Thread.currentThread().getContextClassLoader()));
			} catch (ClassNotFoundException e) {
				throw new IllegalStateException(e.getMessage(), e);
			}
		}
		return getInterfaceClass();
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
	 
	@Override
	public void afterPropertiesSet() throws Exception {
		if( getInterfaceClass() == null && StringUtils.isBlank(this.getInterfaceName()) ){
			throw new IllegalStateException("interfaceClass or interfaceName is null.");
		}
		if( getInterfaceClass() == null){
			this.setInterfaceClass(Class.forName(getInterfaceName(), true, Thread.currentThread().getContextClassLoader()));
		} 
		if( !getInterfaceClass().isInterface() ){
			throw new IllegalStateException(" this field[interfaceClass] value ="+ getInterfaceClass() +"is not a interface.");
		}
		if( getUser() == null || ( StringUtils.isBlank(getUser().getUsername()) && StringUtils.isBlank(getUser().getUserEmail()) ) ){
			throw new IllegalArgumentException("must set the service user config. username|useremail");
		}
		if( getUser().getIsProvider() == null)
			throw new IllegalArgumentException("service user config field=[isProvider] must be set true|false.");
		if(StringUtils.isBlank(getDomain()))
			throw new IllegalArgumentException("service about config field=[domain] must be set.");
		 
	}

 
}
